package cn.xmkeshe.controller;

import cn.xmkeshe.back.IAdminServiceBack;
import cn.xmkeshe.model.Admin;
import cn.xmkeshe.utils.Log;
import cn.xmkeshe.utils.md5.MD5Code;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.HttpCookie;
import java.util.Map;

@Controller
public class AdminLoginController {

  @Resource
  private IAdminServiceBack iAdminServiceBack;

//  登录前
  @RequestMapping("/loginPre")
  @Log(operationName = "登录前",operationType = "管理员")
  public String loginPre(){
    return "/pages/login";
  }

   @RequestMapping("/index")
    public String index() {
        return "/pages/index";
    }

//  Ajax请求
  @RequestMapping("/pages/login")
  @ResponseBody
  @Log(operationName = "登录时校验",operationType = "系统")
  public String login(Admin vo,HttpServletRequest request) {
    String aid = vo.getAid();
    String password = new MD5Code().getMD5ofStr("{"+vo.getPassword()+"}"+aid);
    System.out.println("password:"+password);
    UsernamePasswordToken token = new UsernamePasswordToken(aid, password);
    Subject subject = SecurityUtils.getSubject();
    try {
      subject.login(token);
//      显示头像，须根据session域中是否有admin
      Admin admin = iAdminServiceBack.get(aid);
      System.out.println(admin);
      request.getSession().setAttribute("admin",admin);
      return "success";
    } catch (Exception e) {
      return "error";
    }
  }

//  登录成功
  @RequestMapping("pages/back/indexPre")
  @Log(operationName = "登录成功",operationType = "管理员")
  public String login(){
    return "/pages/back/index";
  }

//  登录注销
  @RequestMapping("pages/logOut")
  @Log(operationName = "注销",operationType = "管理员")
  public String logOut(HttpServletRequest request){
    request.getSession().invalidate();
    return "/pages/login";
  }

//  修改密码
  @RequestMapping("/pages/back/admin/updatePasswordPre")
  @Log(operationName = "修改密码",operationType = "管理员")
  public String updatePasswordPre() {
    return "/pages/back/admin/updatePassword";
  }

  @RequestMapping("/pages/back/admin/updatePassword")
  @ResponseBody
  @Log(operationName = "修改密码成功",operationType = "系统")
  public String updatePassword(String password) {
    String aid = (String) SecurityUtils.getSubject().getPrincipal(); // 取得用户名
    String pass = new MD5Code().getMD5ofStr("{" + password + "}" + aid); // 密码进行加密处理
    if (iAdminServiceBack.updateByPassword(aid, pass)) {
      return "success";
    }
    return "error";
  }
}
